/**
 * 全局生成状态管理
 * 用于跟踪SSE连接和生成状态，避免在认证过期等场景下意外中断
 */

import { defineStore } from 'pinia'
import { ref, readonly } from 'vue'

interface GenerationSession {
	appId: string
	eventSource: EventSource | null
	startTime: number
	userInitiated: boolean // 是否为用户主动发起
}

export const useGenerationStore = defineStore('generation', () => {
	// 当前活跃的生成会话
	const activeSession = ref<GenerationSession | null>(null)

	/**
	 * 开始生成会话
	 */
	const startGeneration = (appId: string, eventSource: EventSource, userInitiated = true) => {
		console.log('🚀 注册生成会话:', { appId, userInitiated })

		activeSession.value = {
			appId,
			eventSource,
			startTime: Date.now(),
			userInitiated
		}
	}

	/**
	 * 结束生成会话
	 */
	const endGeneration = (reason: 'done' | 'user_stop' | 'error' = 'done') => {
		if (activeSession.value) {
			console.log('🏁 结束生成会话:', {
				appId: activeSession.value.appId,
				reason,
				duration: Date.now() - activeSession.value.startTime
			})
		}

		activeSession.value = null
	}

	/**
	 * 检查是否有活跃的生成会话
	 */
	const hasActiveGeneration = () => {
		return activeSession.value !== null
	}

	/**
	 * 获取当前生成的appId
	 */
	const getCurrentAppId = () => {
		return activeSession.value?.appId || null
	}

	/**
	 * 获取当前EventSource
	 */
	const getCurrentEventSource = () => {
		return activeSession.value?.eventSource || null
	}

	/**
	 * 更新EventSource（用于重连场景）
	 */
	const updateEventSource = (eventSource: EventSource) => {
		if (activeSession.value) {
			activeSession.value.eventSource = eventSource
			console.log('🔄 更新生成会话的EventSource')
		}
	}

	/**
	 * 强制清理生成状态（仅在紧急情况下使用）
	 */
	const forceCleanup = () => {
		if (activeSession.value?.eventSource) {
			activeSession.value.eventSource.close()
		}
		activeSession.value = null
		console.warn('⚠️ 强制清理生成状态')
	}

	return {
		activeSession: readonly(activeSession),
		startGeneration,
		endGeneration,
		hasActiveGeneration,
		getCurrentAppId,
		getCurrentEventSource,
		updateEventSource,
		forceCleanup
	}
})
